package com.mh.web.controller.system;

import com.mh.common.core.domain.BaseResp;
import com.mh.common.utils.ChainedMap;
import com.mh.common.utils.ServletUtils;
import com.mh.framework.service.SysPermsService;
import com.mh.system.domain.LoginUserDetails;
import com.mh.system.domain.SysMenu;
import com.mh.system.domain.SysUser;
import com.mh.system.domain.vo.LoginBody;
import com.mh.system.domain.vo.RouterVO;
import com.mh.system.service.SysLoginService;
import com.mh.system.service.SysMenuService;
import com.mh.system.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService loginService;

    @PostMapping("/login")
    public ChainedMap login(@RequestBody LoginBody loginBody) {
        //生成Token(调用SysLoginService-->再调用TokenService)
        String token = loginService.login(loginBody);

        //往前端响应一个Token,封装到map集合中
        return ChainedMap.create().set("token",token);
    }

    //注入通用获取权限信息的类
    @Autowired
    private SysPermsService permsService;

    @Autowired
    private TokenService tokenService;

    @GetMapping("/getInfo")
    public ChainedMap getInfo() {


        System.out.println("1./getInfo,获取req:"+ServletUtils.getRequest());

        //通过工具类ServletUtils获取req(中的Token),再调用TokenService获取用户信息
        LoginUserDetails loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();

        //通过通用类,获取角色集合
        Set<String> roles = permsService.getRoles(user);
        //通过通用类,获取权限集合
        Set<String> perms = permsService.getPerms(user);

        ChainedMap map = ChainedMap.create().set("code", 200).set("msg","操作成功");
        map.put("user",user);
        map.put("roles",roles);
        map.put("permissions",perms);

        return map;
    }

    @Autowired
    private SysMenuService menuService;
    @GetMapping("/getRouters")
    public BaseResp getRouters(){
        LoginUserDetails loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();

        //获取菜单列表
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        //将获取到的菜单列表转换为 前端所需的菜单导航列表
        List<RouterVO> routerVOS = menuService.buildMenus(menus);

        return BaseResp.success(routerVOS);
    }
}
